package com.cain.threadpool.service;

import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

import com.cain.threadpool.entity.CainResult;
import com.cain.threadpool.entity.FaceVerificationResult;
import com.cain.threadpool.entity.UserInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;

/**
 * @author Cain.chi
 * @date 2019/7/4 17:47
 * @description 登录service
 */
@Service
public class LoginService {

    Logger logger = LoggerFactory.getLogger(LoginService.class);

    @Autowired
    FaceVerifiationService faceVerifiationService;

    @Autowired
    ApplicationContext applicationContext;

    public CainResult login(UserInfo userInfo) {
        CainResult cainResult = new CainResult();
        LoginService loginService = applicationContext.getBean(LoginService.class);
        Future<FaceVerificationResult> onlineFaceVerificationResult = loginService.getOnlineFaceVerificationResult(userInfo);
        try {
            // 模拟从数据获取数据判断用户账号状态是否冻结的消耗时间
            Thread.sleep(4000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        FaceVerificationResult faceVerificationResult = null;
        try {
            // 如果3秒还没有结果直接人脸识别失败
            faceVerificationResult = onlineFaceVerificationResult.get(3, TimeUnit.SECONDS);
        } catch (Exception e) {
            logger.error("获取人脸识别结果失败");
            // 异常处理
        }
        if (faceVerificationResult != null) {
            cainResult.setCode(faceVerificationResult.getCode());
            cainResult.setMessage(faceVerificationResult.getMessage());
        }
        return cainResult;
    }

    @Async
    public Future<FaceVerificationResult> getOnlineFaceVerificationResult(UserInfo userInfo) {
        logger.info("异步执行");
        FaceVerificationResult result = faceVerifiationService.getResult(userInfo);
        return new AsyncResult<>(result);
    }
}
